using System.Threading.Tasks;
using Auth0.OidcClient;
using DailyPoetryX.Confidential;
using DailyPoetryX.Services;

namespace DailyPoetryX.Droid.Services.Implementations {
    /// <summary>
    /// 身份验证服务。
    /// </summary>
    public class AuthenticationServiceAndroid : IAuthenticationService {
        /******** 公开变量 ********/

        /******** 私有变量 ********/

        /// <summary>
        /// Auth0客户端。
        /// </summary>
        private Auth0Client _auth0Client;

        /******** 继承方法 ********/

        /// <summary>
        /// 验证身份。
        /// </summary>
        /// <returns>身份验证结果。</returns>
        public async Task<AuthenticationResult> Authenticate() {
            var auth0LoginResult =
                await _auth0Client.LoginAsync(new {
                    audience = AuthenticationSettings.Audience
                });
            
            AuthenticationResult authenticationResult;
            if (!auth0LoginResult.IsError) {
                authenticationResult = new AuthenticationResult() {
                    AccessToken = auth0LoginResult.AccessToken
                };
            } else
                authenticationResult =
                    new AuthenticationResult(auth0LoginResult.IsError,
                        auth0LoginResult.Error);
            
            return authenticationResult;
        }

        /******** 公开方法 ********/

        /// <summary>
        /// 身份验证服务。
        /// </summary>
        public AuthenticationServiceAndroid() {
            _auth0Client = new Auth0Client(new Auth0ClientOptions {
                Domain = AuthenticationSettings.Domain,
                ClientId = AuthenticationSettings.ClientId
            });
        }

        /******** 私有方法 ********/
    }
}